import tkinter as tk  # GUI 界面库
from tkinter import ttk, messagebox  # 额外的 GUI 组件
from PIL import Image, ImageTk  # 处理图片
import requests  # 发送 API 请求获取实时汇率
import matplotlib.pyplot as plt  # 绘制汇率趋势图
import datetime  # 处理日期
import pandas as pd  # 数据分析
from io import BytesIO  # 处理 API 返回的数据流

# ------------------- API 相关 -------------------
API_URL = "https://api.frankfurter.app/latest"  # 实时汇率 API
HISTORICAL_API_URL = "https://api.frankfurter.app/{date}"  # 获取历史汇率 API

def get_exchange_rate(base, target):
    """ 获取实时汇率 """
    try:
        response = requests.get(f"{API_URL}?from={base}&to={target}")  # 发送 API 请求
        data = response.json()  # 解析 JSON 数据
        return data['rates'][target]  # 提取目标汇率
    except Exception as e:
        messagebox.showerror("错误", f"无法获取汇率数据: {e}")  # 显示错误信息
        return None

def get_historical_rates(base, target):
    """ 获取近 7 天的汇率数据 """
    rates = []
    dates = []
    for i in range(7, 0, -1):  # 过去 7 天的数据
        date = (datetime.datetime.today() - datetime.timedelta(days=i)).strftime("%Y-%m-%d")
        try:
            response = requests.get(f"{HISTORICAL_API_URL.format(date=date)}?from={base}&to={target}")
            data = response.json()
            if 'rates' in data and target in data['rates']:
                rates.append(data['rates'][target])
                dates.append(date)
        except:
            continue
    return dates, rates

# ------------------- GUI 界面 -------------------
class CurrencyConverterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("汇率兑换工具")  # 窗口标题
        self.root.geometry("500x600")  # 窗口大小
        self.root.configure(bg="white")  # 背景颜色

        # 加载背景图片
        self.bg_image = Image.open(r"D:\作业\hd\2025\rabbit.jpg")  # 读取背景图片
        self.bg_image = self.bg_image.resize((500, 600), Image.LANCZOS)  # 调整尺寸
        self.bg_photo = ImageTk.PhotoImage(self.bg_image)  # 转换为 Tkinter 可用格式
        self.bg_label = tk.Label(root, image=self.bg_photo)  # 创建背景图片标签
        self.bg_label.place(x=0, y=0, relwidth=1, relheight=1)  # 让图片填充整个窗口

        # 创建 UI 组件
        self.create_widgets()

    def create_widgets(self):
        """ 创建 UI 组件 """
        label_title = tk.Label(self.root, text="货币兑换", font=("Arial", 18, "bold"), bg="white")
        label_title.pack(pady=10)

        # 兑换金额输入框
        self.amount_var = tk.StringVar()
        entry_amount = ttk.Entry(self.root, textvariable=self.amount_var, font=("Arial", 14))
        entry_amount.pack(pady=10)

        # 选择货币
        self.currency_var1 = tk.StringVar(value="USD")
        self.currency_var2 = tk.StringVar(value="CNY")
        currency_options = ["USD", "CNY", "EUR", "JPY", "GBP"]

        self.combo_currency1 = ttk.Combobox(self.root, textvariable=self.currency_var1, values=currency_options, state="readonly")
        self.combo_currency2 = ttk.Combobox(self.root, textvariable=self.currency_var2, values=currency_options, state="readonly")
        self.combo_currency1.pack(pady=5)
        self.combo_currency2.pack(pady=5)

        # 兑换按钮
        btn_convert = ttk.Button(self.root, text="兑换", command=self.convert_currency)
        btn_convert.pack(pady=10)

        # 兑换结果
        self.result_label = tk.Label(self.root, text="", font=("Arial", 14), bg="white")
        self.result_label.pack(pady=10)

        # 其他功能按钮
        btn_trend = ttk.Button(self.root, text="汇率趋势", command=self.show_exchange_trend)
        btn_trend.pack(pady=5)

        btn_advice = ttk.Button(self.root, text="投资建议", command=self.show_investment_advice)
        btn_advice.pack(pady=5)

    def convert_currency(self):
        """ 货币兑换计算 """
        try:
            amount = float(self.amount_var.get())  # 获取输入金额
            base_currency = self.currency_var1.get()
            target_currency = self.currency_var2.get()

            if base_currency == target_currency:
                messagebox.showwarning("提示", "请选择不同的货币进行兑换！")
                return

            rate = get_exchange_rate(base_currency, target_currency)  # 获取汇率
            if rate:
                converted_amount = round(amount * rate, 2)  # 计算兑换金额
                self.result_label.config(text=f"{amount} {base_currency} = {converted_amount} {target_currency}")

        except ValueError:
            messagebox.showerror("错误", "请输入有效的金额！")  # 处理输入错误

    def show_exchange_trend(self):
        """ 显示汇率趋势图 """
        base_currency = self.currency_var1.get()
        target_currency = self.currency_var2.get()
        
        dates, rates = get_historical_rates(base_currency, target_currency)  # 获取历史汇率
        
        if rates:
            plt.figure(figsize=(6, 4))
            plt.plot(dates, rates, marker='o', linestyle='-')
            plt.xlabel("日期")
            plt.ylabel(f"{base_currency} -> {target_currency} 汇率")
            plt.title("汇率趋势")
            plt.xticks(rotation=45)
            plt.grid()
            plt.show()
        else:
            messagebox.showerror("错误", "无法获取汇率数据！")

    def show_investment_advice(self):
        """ 提供投资建议 """
        base_currency = self.currency_var1.get()
        target_currency = self.currency_var2.get()
        dates, rates = get_historical_rates(base_currency, target_currency)

        if len(rates) < 2:
            messagebox.showerror("错误", "汇率数据不足，无法提供建议！")
            return

        if rates[-1] > rates[-2]:  # 判断汇率趋势
            advice = f"{target_currency} 汇率正在上涨，建议持有。"
        else:
            advice = f"{target_currency} 汇率下降，建议兑换 {base_currency}。"

        messagebox.showinfo("投资建议", advice)

# 运行程序
if __name__ == "__main__":
    root = tk.Tk()
    app = CurrencyConverterApp(root)
    root.mainloop()
